<?php

namespace Common\Logic;


class SmsLogic extends BaseLogic
{

    static $apiUri = "https://sms.yunpian.com/v2/sms";
    static $apiKey = "fbab122ab1adb60e39dad9c544c455cf";//营销key
    static $sysApiKeu = "74699008c9507c2da9b473d972e00531";//系统key

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 发送一条短信验
     * @param $moblie
     * @param $text
     * @param bool $isSysType
     * @return mixed
     */
    public function singleSend($moblie, $text, $isSysType = true)
    {
        if (empty($moblie)) {
            return static::$res->err("手机号不能为空");
        }

        if (!validate($moblie, "mobile")) {
            return static::$res->err("请输入正确的手机号");
        }

        if (empty($text)) {
            return static::$res->err("短信内容不能为空");
        }

        $url = static::$apiUri . "/single_send.json";

        $apiKey = $isSysType ? static::$sysApiKeu : static::$apiKey;

        $param = array(
            "apikey" => $apiKey,
            "mobile" => $moblie,
            "text" => $text
        );

        $sendRes = $this->post($url, $param);

        if ($sendRes['code']) {
            return static::$res->err("短信发送失败:" . $sendRes['msg']);
        }
        return static::$res->suc("短信发送成功");
    }

    /**
     * curl，因为有其它的body体，需要独立一个
     * @param $url
     * @param $param
     * @param int $isPost
     * @param int $timeout
     * @return mixed
     */
    public function post($url, $param, $isPost = 1, $timeout = 60)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, $isPost);

        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Accept:application/json;charset=utf-8",
            "Content-Type:application/x-www-form-urlencoded;charset=utf-8"
        ));
        $contents = curl_exec($ch);
        curl_close($ch);
        return json_decode($contents, true);
    }


}
